import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Select,

  Checkbox, DatePicker, BackTop, TreeSelect,
} from 'antd';
import { renderTreeNodes} from '@/utils/utils';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import request from '@/utils/request';
import './index.less'
import ReactEcharts from 'echarts-for-react';
import { routerRedux } from 'dva/router';
const { Option } = Select;
const FormItem = Form.Item;

@connect(({ level_annual_billings2, loading,global,owner }) => ({
  level_annual_billings2,
  global,
  owner,
  loading: loading.models.level_annual_billings2,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      data:[],
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      maxWidth:200,
      all_users:[],
    };

  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      level_annual_billings2: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.ant-table-body');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        level_annual_billings2: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'level_annual_billings2/changeTableY',
      });
      dispatch({
        type: 'level_annual_billings2/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'level_annual_billings2/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    this.setState({
      maxWidth: document.querySelector('.table-page').offsetWidth-20
    },function () {
      console.log('maxWidth',this.state.maxWidth)
    })


    const that = this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }

    });

  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'level_annual_billings2/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    dispatch({
      type: 'level_annual_billings2/changeTableY',
    });
  };


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'level_annual_billings2/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        const table = document.querySelector('.ant-table-body');
        setTimeout(() => {
          table.scrollTop = 0;
        }, 0);
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const data = this.state.data;
    const {
      form: { getFieldDecorator },
      level_annual_billings2: { searchParams },
    } = this.props;
    let  regions=[];
    for(let i=0;i<searchParams.region_ids.length;i++){
      regions.push(`${searchParams.region_ids[i]}$${searchParams.region_names[i]}`)
    }
    return (
      <Form layout="inline" className="search-form">
        <div>
          <FormItem label="区域">
            {getFieldDecorator('region_ids', {
              initialValue: regions,
            })(
              <TreeSelect
                style={{width:'510px'}}
                allowClear
                treeDefaultExpandAll
                multiple
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                showSearch
              >
                {renderTreeNodes(data)}
              </TreeSelect>,
            )}
          </FormItem>
          <FormItem label={''}>
            {getFieldDecorator('filter', {
              initialValue: searchParams.filter,
            })(
              <Radio.Group >
                <Radio.Button  value={0}>全部</Radio.Button >
                <Radio.Button  value={2}>只看有二阶区域</Radio.Button >
                <Radio.Button  value={3}>只看有三阶区域</Radio.Button >
              </Radio.Group>
            )}
          </FormItem>
        </div>
        <FormItem label={'年份'}>
          {getFieldDecorator('year', {
            initialValue: searchParams.year,
          })(
            <Select style={{width:'205px'}} allowClear={false}>
              <Option value={'2017'}>2017年</Option>
              <Option value={'2018'}>2018年</Option>
              <Option value={'2019'}>2019年</Option>
              <Option value={'2020'}>2020年</Option>
              <Option value={'2021'}>2021年</Option>
            </Select>
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;
                console.log(fieldsValue)
                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  region_ids:fieldsValue.region_ids?fieldsValue.region_ids.map((item,index)=>{
                    return item.split('$')[0]
                  }):[],
                  region_names:fieldsValue.region_ids?fieldsValue.region_ids.map((item,index)=>{
                    return item.split('$')[1]
                  }):[],
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Button type={'primary'} className={'btn-cyan'} style={{ marginLeft: 8 }} icon='export' onClick={()=>{message.info('功能正在开发中')}}>
            导出报表
          </Button>
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'level_annual_billings2/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('新建设备成功');
        that.setState({
          addModal: false,
        });
        const {
          level_annual_billings2: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      region_ids:[],
      region_names:[],
      year: moment(new Date()).format('YYYY'),
      filter:0
    });
  };

  dynamic=()=>{
    const {
      level_annual_billings2: { originData},
    } = this.props;
    function array2obj (array, key) {
      var resObj = {}
      for (var i = 0; i < array.length; i++) {
        resObj[array[i][key]] = array[i]
      }
      return resObj
    }
    var seriesData = [{
      name: "一阶",
      value: 0
    }, {
      name: "二阶",
      value: 0
    }, {
      name: "三阶",
      value: 0
    }];
    for(let i=0;i<originData.length;i++){
      seriesData[0].value+=Number(originData[i].level_one_account_count);
      seriesData[1].value+=Number(originData[i].level_two_account_count);
      seriesData[2].value+=Number(originData[i].level_three_account_count);
    }
    let total=0;
    for(let i=0;i<seriesData.length;i++){
      total+=Number(seriesData[i].value);
    }
    let legendData = ["一阶", "二阶", "三阶"]
    let colorList = [ '#73ACFF', '#FDD56A',  '#FD866A'];
    let objData = array2obj(seriesData, 'name')
    let option = {
      backgroundColor: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 1,
        y2: 1,
        colorStops: [{
          offset: 0,
          color: '#0f2c70' // 0% 处的颜色
        }, {
          offset: 1,
          color: '#091732' // 100% 处的颜色
        }],
        globalCoord: false // 缺省为 false
      },
      title: {
        text: total,
        x: 'center',
        y: 'center',
        textStyle: {
          color: '#fff',
          fontSize:30
        },
        subtext: '阶梯居民用户数',
        subtextStyle: {
          color: '#e8e8e8',
          fontSize: 18
        },
      },
      tooltip: {
        trigger: 'item',
        borderColor: 'rgba(255,255,255,.3)',
        backgroundColor: 'rgba(13,5,30,.6)',
        borderWidth: 1,
        padding: 5,
        formatter: function(parms) {
          var str = parms.marker + "" + parms.data.name + "</br>" +
            "数量：" + parms.data.value + " 户</br>" +
            "占比：" + parms.percent + " %";
          return str;
        }
      },
      legend: {
        type: "scroll",
        align: 'auto',
        bottom:'10%',
        textStyle: {
          color: '#fff',
          fontSize:18
        },
        formatter: function (name) {
          return `${name} ${objData[name].value} 户`
        },
        data: legendData
      },
      series: [{
        type: 'pie',
        z: 3,
        center: ['50%', '50%'],
        radius: ['35%', '55%'],
        clockwise: true,
        avoidLabelOverlap: true,
        hoverOffset: 15,
        itemStyle: {
          normal: {
            color: function(params) {
              return colorList[params.dataIndex]
            }
          }
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{a|{b}：{d} %}',
          rich: {
            hr: {
              backgroundColor: 't',
              borderRadius: 3,
              width: 3,
              height: 3,
              padding: [3, 3, 0, -12]
            },
            a: {
              padding: [-30, 15, -20, 15],
              fontSize: 16,
            }
          }
        },
        labelLine: {
          normal: {
            length: 20,
            length2: 30,
            lineStyle: {
              width: 1
            }
          }
        },
        data: seriesData
      }, {
        name:'第一层环',
        type: 'pie',
        z: 2,
        tooltip:{
          show:false
        },
        center: ['50%', '50%'],
        radius: ['45%', '58%'],
        hoverAnimation: false,
        clockWise: false,
        itemStyle: {
          normal: {
            // shadowBlur: 40,
            // shadowColor: 'rgba(0, 255, 255,.3)',
            color: 'rgba(1,15,80,.4)',
          },
          emphasis:{
            color: 'rgba(1,15,80,.4)',
          }
        },
        label: {
          show: false
        },
        data: [100]
      }, {
        name:'第二层环',
        type: 'pie',
        z: 1,
        tooltip:{
          show:false
        },
        center: ['50%', '50%'],
        radius: ['58%', '76%'],
        hoverAnimation: false,
        clockWise: false,
        itemStyle: {
          normal: {
            // shadowBlur: 40,
            // shadowColor: 'rgba(0, 255, 255,.3)',
            color: 'rgba(0,15,69,.2)',
          },
          emphasis:{
            color: 'rgba(0,15,69,.2)',
          }
        },
        label: {
          show: false
        },
        data: [100]
      }]
    };
    return option
  }
  handleClick = (key,region_id,region_name,level) => {
    console.log('key)', key);
    const { panes, routerMapping } = this.props.global;
    const {dispatch} =this.props;
    const activeKey = key;
    const that=this;
    if(level==='一阶'){
      level=1
    }else if(level==='二阶'){
      level=2
    }else if(level==='三阶'){
      level=3
    }
    if (find(panes, o => o.key == activeKey)) {
      console.log('已经存在');
    } else {
      panes.push({
        title: find(routerMapping, o => o.path == activeKey).name,
        content: 'New Tab Pane',
        key: activeKey,
      });
    }
    dispatch(routerRedux.push(activeKey));
    dispatch({
      type: 'global/changePanesAndActive',
      payload: { panes, activeKey },
      callback:function() {
        const {
          level_annual_billings2: { searchParams},
          global:{gridTableW}
        } = that.props;
        const sendSearchParams= {
          region_id:region_id,
          region_name:region_name,
          status:'0',
          balance_status:'0',
          caliber:'',
          name:'',
          mobile:'',
          meter_number:'',
          address:'',
          filter_level:level,
          filter_year:searchParams.year,
          page: 1,
          per_page: 50,
        };
        console.log('sendSearchParams', sendSearchParams);
        dispatch({
          type: 'owner/changeLoadedFalse',
          callback:function() {
            dispatch({
              type: 'owner/changeSearchParams',
              payload: sendSearchParams,
            });
          }
        });

      }
    });
  };
  render() {
    const that = this;
    const {
      level_annual_billings2: { data, loading, tableY, meta, summary, selectedRowKeys, additional },
      global:{gridTableW}
    } = this.props;
    const columns = [
      {
        title: '排名',
        dataIndex: 'myId',
        width: 70,
        render: (value, row, index) => {
          const obj = {
            children: row.index,
            props: {
              rowSpan:row.level_name==='一阶'?4:0
            },
          };
          return obj;
        }
      },
      {
        title: '区域名称',
        dataIndex: 'region_name',
        width: '100',
        render: (value, row, index) => {
          const obj = {
            children: <span title={'查看该区域所有水表'}  style={{color:'blue',cursor:'pointer'}} onClick={()=>{
              this.handleClick('/owner',row.region_id,value,'')
            }}>{value}</span>,
            props: {
              rowSpan:row.level_name==='一阶'?4:0
            },
          };
          return obj;
        }
      },
      {
        width: '120',
        title: '用水量阶梯',
        dataIndex: 'level_name',
        render:(value,row)=>{
          return (value==='合计'||row.count===0)?value:<span style={{color:'blue',cursor:'pointer',fontWeight:'bold'}}  onClick={()=>{
            this.handleClick('/owner',row.region_id,row.region_name,value)
          }}>{value}</span>
        }
      },
      {
        width: '120',
        title: '用水量(m³)',
        dataIndex: 'consumption',
      },
      {
        width: '120',
        title: '水费',
        dataIndex: 'fee',
      },
      {
        width: '120',
        title: '污水处理费',
        dataIndex: 'sewage_fee',
        render: (value, row, index) => {
          return <p style={{textAlign:'center',marginBottom:'0'}}>{value}</p>
        }
      },
    ];
    let tableX=600

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>阶梯水费报表</span>
      </div>
      <div className="table-page">
        <div className="table-condition">
          {this.renderSimpleForm()}
        </div>
        <div style={{display:'flex',minHeight:tableY+'px'}}>
          <div style={{flex:1}}>
            <Table
              style={{color: '#fff',maxWidth:this.state.maxWidth+'px'}}
              className="custom-small-table meter-table vendor-meter no-interval level_annual_billings-report"
              loading={loading}
              rowKey={'myId'}
              dataSource={[...data]}
              columns={columns}
              pagination={false}
              size="small"
              scroll={{x: tableX, y: tableY}}
            />
          </div>
          <div style={{flex:1}}>
            <ReactEcharts
              option={this.dynamic()}
              style={{ height: '100%', width: '100%' }}
              theme='my_theme'
              //onChartReady={this.onChartReadyCallback}
              //onEvents={EventsDict}
            />
          </div>
        </div>
        <BackTop  target={()=>{return document.querySelector('.ant-table-body')}}/>
      </div>
    </div>;
  }
}

export default BasicList;
